package com.neuedu.spring;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author 金山
 * 项目：spring-learn
 * site: https://blog.fulfill.com.cn
 * 描述
 * @data 2025/3/1310:30
 */
@Configuration
@ComponentScan("com.neuedu.spring")
public class SpringMyBatisConfiguration {


    /**
     * 数据源
     * @return
     */
    @Bean
    public DataSource dataSource(){

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/his?useSSL=false");

        return dataSource;
    }

    /**
     * SqlSessionFactory
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory( DataSource dataSource ) throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //设置 mybaits的 settingxxxxxx
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setLogImpl(StdOutImpl.class);
        sqlSessionFactoryBean.setConfiguration(configuration);

        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));


        return sqlSessionFactoryBean.getObject();

    }

    /**
     * 扫描 MyBatis中 Mapper的 包，并注册在 IOC容器中
     * @param sqlSessionFactory
     * @return
     */
    @Bean
    public MapperScannerConfigurer mapperSanccer(SqlSessionFactory sqlSessionFactory){
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();


        //创建一堆 Mapper的扫描

        scannerConfigurer.setBasePackage("com.neuedu.spring.mybatis.mapper");
        scannerConfigurer.setSqlSessionFactory(sqlSessionFactory);

        return  scannerConfigurer;
    }









}
